﻿
namespace BasicHostModule.Module
{
    public class TaskHostedService : IHostedService
    {
        private Timer _Timer;

        public ILogger<TaskHostedService> logger { get; set; }

        public TaskHostedService(ILogger<TaskHostedService> logger)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 应用程序运行的时候，调用
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("后台任务启动.....");
            _Timer = new Timer(DoWork, "执行", TimeSpan.Zero, TimeSpan.FromSeconds(2)); 
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            Console.WriteLine($"任务执行： {state.ToString()} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
        }

        /// <summary>
        /// 应用程序停止的时候，调用
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("后台任务停止......");
            _Timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }
    }
}
